module key_filter(
	clk,
	rst_n,
	key,
	key_p_flag,
	key_r_flag,
	key_state
);

	input clk;
	input rst_n;
	input key;
	output reg key_p_flag;
	output reg key_r_flag;
	output reg key_state;
	
	reg sync_d0_key;
	reg sync_d1_key;
	reg r_key;
	
	wire pedge_key;// 上升沿
	wire nedge_key;// 下降沿
	
	localparam IDLE = 0;
	localparam P_FILTER = 1;
	localparam WAIT_R = 2;
	localparam R_FILTER = 3;
	reg [1:0] state;
	
	parameter MCNT = 1_000_000 - 1;
	reg [29:0] cnt;
	
	wire time_20ms_reached;

	always@(posedge clk)
		sync_d0_key <= key;
	always@(posedge clk)
		sync_d1_key <= sync_d0_key;
	always@(posedge clk)
		r_key <= sync_d1_key;
	
	assign nedge_key = (sync_d1_key == 0) && (r_key == 1);
	assign pedge_key = (sync_d1_key == 1) && (r_key == 0);
	
	always@(posedge clk or negedge rst_n)
		if(!rst_n)begin
			state <= IDLE;
			key_p_flag <= 0;
			key_r_flag <= 0;
			cnt <= 0;
			key_state <= 1;
		end
		else begin
			case(state)
				IDLE:begin
					key_r_flag <= 1'd0;
					if(nedge_key)
						state <= P_FILTER;
				end
				P_FILTER:begin
					if(time_20ms_reached) begin
						state <= WAIT_R;
						key_p_flag <= 1'd1;
						key_state <= 0;
						cnt <= 0;
					end
					else if(pedge_key)begin
						state <= IDLE;
						cnt <= 0;
					end
					else begin
						state <= P_FILTER;
						cnt <= cnt +1'd1;
					end
				end
				WAIT_R:begin
					key_p_flag <= 1'd0;
					if(pedge_key)
						state <= R_FILTER;
				end
				R_FILTER:begin
					if(time_20ms_reached)begin
						key_r_flag <= 1'd1;
						key_state <= 1;
						state <= IDLE;
						cnt <= 0;
					end
					else if(nedge_key)begin
						state <= WAIT_R;
						cnt <= 0;
					end
					else begin
						state <= R_FILTER;
						cnt <= cnt + 1'd1;
					end
				end
			endcase
		end
		
//		always@(posedge clk or negedge rst_n)
//			if(!rst_n)
//				cnt <= 0;
//			else if((state == R_FILTER)||(state == P_FILTER))
//				cnt <= cnt+1'd1;
//			else
//				cnt <= 0;
		
		assign time_20ms_reached = (cnt >= MCNT);
endmodule
